<script setup>
import { ref, computed, onMounted } from 'vue';
import AudioService from '../../services/AudioService';

// 定义props
const props = defineProps({
  player: {
    type: Object,
    required: true
  },
  opponent: {
    type: Object,
    required: true
  }
});

// 定义emits
const emit = defineEmits(['battle-end']);

// 战斗状态
const battleLog = ref([]);
const currentTurn = ref('player'); // player or opponent
const isActionInProgress = ref(false);
const battleResult = ref(null); // win, lose, draw
const gameOver = ref(false);

// 动画状态
const playerAttacking = ref(false);
const opponentAttacking = ref(false);
const playerUsingSkill = ref(false);
const opponentUsingSkill = ref(false);
const playerHit = ref(false);
const opponentHit = ref(false);

// 角色当前状态（避免直接修改props）
const playerState = ref({
  ...props.player,
  currentHealth: props.player.health,
  currentChakra: props.player.chakra
});

const opponentState = ref({
  ...props.opponent,
  currentHealth: props.opponent.health,
  currentChakra: props.opponent.chakra
});

// 计算属性 - 角色生命值百分比
const playerHealthPercent = computed(() => {
  return (playerState.value.currentHealth / playerState.value.health) * 100;
});

const opponentHealthPercent = computed(() => {
  return (opponentState.value.currentHealth / opponentState.value.health) * 100;
});

// 计算属性 - 角色查克拉百分比
const playerChakraPercent = computed(() => {
  return (playerState.value.currentChakra / playerState.value.chakra) * 100;
});

const opponentChakraPercent = computed(() => {
  return (opponentState.value.currentChakra / opponentState.value.chakra) * 100;
});

// 添加战斗日志
const addBattleLog = (message) => {
  battleLog.value.push({
    id: Date.now(),
    message,
    timestamp: new Date()
  });
  // 限制日志数量
  if (battleLog.value.length > 20) {
    battleLog.value.shift();
  }
};

// 玩家攻击
const playerAttack = () => {
  if (isActionInProgress.value || gameOver.value) return;
  
  isActionInProgress.value = true;
  playerAttacking.value = true;
  
  try {
    // 播放攻击音效
    AudioService.playSound('attack');
    
    setTimeout(() => {
      try {
        // 基础伤害计算 - 添加性能优化的随机数生成
        const randomFactor = (Math.random() - 0.5) * 2; // -1 到 1
        const baseDamage = Math.floor(playerState.value.strength * 0.8 + Math.abs(randomFactor) * playerState.value.strength * 0.2);
        
        // 对手受伤
        opponentState.value.currentHealth = Math.max(0, opponentState.value.currentHealth - baseDamage);
        
        // 播放伤害音效
        AudioService.playSound('damage');
        opponentHit.value = true;
        
        addBattleLog(`${playerState.value.name} 发动攻击，对 ${opponentState.value.name} 造成 ${baseDamage} 点伤害！`);
        
        // 重置动画状态
        setTimeout(() => {
          playerAttacking.value = false;
          opponentHit.value = false;
        }, 500);
        
        // 检查战斗是否结束
        if (opponentState.value.currentHealth <= 0) {
          endBattle('win');
          return;
        }
        
        // 等待一段时间后切换到对手回合
        setTimeout(() => {
          currentTurn.value = 'opponent';
          opponentTurn();
        }, 1000);
      } catch (error) {
        console.error('攻击过程中发生错误:', error);
        resetBattleState();
      }
    }, 800);
  } catch (error) {
    console.error('启动攻击动作时发生错误:', error);
    resetBattleState();
  }
};

// 重置战斗状态（错误恢复）
const resetBattleState = () => {
  isActionInProgress.value = false;
  playerAttacking.value = false;
  opponentAttacking.value = false;
  playerUsingSkill.value = false;
  opponentUsingSkill.value = false;
  playerHit.value = false;
  opponentHit.value = false;
  
  // 确保回合状态有效
  if (!gameOver.value && ['player', 'opponent'].includes(currentTurn.value)) {
    currentTurn.value = 'player';
  }
};

// 玩家使用技能
const playerUseSkill = (skillIndex) => {
  if (isActionInProgress.value || gameOver.value) return;
  
  // 简单的查克拉消耗机制
  const chakraCost = 20;
  
  if (playerState.value.currentChakra < chakraCost) {
    addBattleLog('查克拉不足，无法使用技能！');
    return;
  }
  
  isActionInProgress.value = true;
  playerUsingSkill.value = true;
  
  // 播放技能音效
  AudioService.playSound('skill');
  
  setTimeout(() => {
    playerState.value.currentChakra -= chakraCost;
    
    // 技能伤害比普通攻击高
    const skillDamage = Math.floor(playerState.value.strength * 1.2 + Math.random() * playerState.value.strength * 0.5);
    const skillName = playerState.value.skills[skillIndex] || '未知技能';
    
    // 对手受伤
    opponentState.value.currentHealth = Math.max(0, opponentState.value.currentHealth - skillDamage);
    
    // 播放伤害音效
    AudioService.playSound('damage');
    opponentHit.value = true;
    
    addBattleLog(`${playerState.value.name} 使用 ${skillName}，对 ${opponentState.value.name} 造成 ${skillDamage} 点伤害！`);
    
    // 重置动画状态
    setTimeout(() => {
      playerUsingSkill.value = false;
      opponentHit.value = false;
    }, 500);
    
    // 检查战斗是否结束
    if (opponentState.value.currentHealth <= 0) {
      endBattle('win');
      return;
    }
    
    // 等待一段时间后切换到对手回合
    setTimeout(() => {
      currentTurn.value = 'opponent';
      opponentTurn();
    }, 1000);
  }, 1000);
};

// 对手回合
const opponentTurn = () => {
  if (gameOver.value) return;
  
  isActionInProgress.value = true;
  
  // 简单AI：50%几率使用普通攻击，50%几率使用技能（如果有足够查克拉）
  const actionType = Math.random() > 0.5 && opponentState.value.currentChakra >= 20 ? 'skill' : 'attack';
  
  if (actionType === 'skill') {
    opponentUsingSkill.value = true;
    AudioService.playSound('skill');
    
    setTimeout(() => {
      opponentState.value.currentChakra -= 20;
      const damage = Math.floor(opponentState.value.strength * 1.2 + Math.random() * opponentState.value.strength * 0.5);
      const message = `${opponentState.value.name} 使用了技能，对 ${playerState.value.name} 造成 ${damage} 点伤害！`;
      
      // 玩家受伤
      playerState.value.currentHealth = Math.max(0, playerState.value.currentHealth - damage);
      AudioService.playSound('damage');
      playerHit.value = true;
      
      addBattleLog(message);
      
      // 重置动画状态
      setTimeout(() => {
        opponentUsingSkill.value = false;
        playerHit.value = false;
      }, 500);
      
      // 检查战斗是否结束
      if (playerState.value.currentHealth <= 0) {
        endBattle('lose');
        return;
      }
      
      // 回合结束，恢复玩家行动能力
      setTimeout(() => {
        currentTurn.value = 'player';
        isActionInProgress.value = false;
      }, 1000);
    }, 1000);
  } else {
    opponentAttacking.value = true;
    AudioService.playSound('attack');
    
    setTimeout(() => {
      const damage = Math.floor(opponentState.value.strength * 0.8 + Math.random() * opponentState.value.strength * 0.4);
      const message = `${opponentState.value.name} 发动攻击，对 ${playerState.value.name} 造成 ${damage} 点伤害！`;
      
      // 玩家受伤
      playerState.value.currentHealth = Math.max(0, playerState.value.currentHealth - damage);
      AudioService.playSound('damage');
      playerHit.value = true;
      
      addBattleLog(message);
      
      // 重置动画状态
      setTimeout(() => {
        opponentAttacking.value = false;
        playerHit.value = false;
      }, 500);
      
      // 检查战斗是否结束
      if (playerState.value.currentHealth <= 0) {
        endBattle('lose');
        return;
      }
      
      // 回合结束，恢复玩家行动能力
      setTimeout(() => {
        currentTurn.value = 'player';
        isActionInProgress.value = false;
      }, 1000);
    }, 800);
  }
};

// 结束战斗
const endBattle = (result) => {
  battleResult.value = result;
  gameOver.value = true;
  isActionInProgress.value = false;
  
  let resultMessage;
  if (result === 'win') {
    resultMessage = `${playerState.value.name} 获胜！你成功击败了 ${opponentState.value.name}！`;
    // 播放胜利音效
    AudioService.playSound('victory');
  } else if (result === 'lose') {
    resultMessage = `${opponentState.value.name} 获胜！你被击败了，但不要放弃，继续努力！`;
    // 播放失败音效
    AudioService.playSound('defeat');
  }
  
  addBattleLog(resultMessage);
  
  // 通知父组件战斗结束
  setTimeout(() => {
    emit('battle-end', { result });
  }, 2000);
};

// 初始化战斗
onMounted(() => {
  // 初始化音频服务
  AudioService.init().then(() => {
    console.log('音频服务初始化完成');
    // 播放背景音乐
    AudioService.playBackgroundMusic();
  }).catch(error => {
    console.warn('音频服务初始化失败，但游戏仍可继续:', error);
  });
  
  addBattleLog(`战斗开始！${playerState.value.name} vs ${opponentState.value.name}`);
});

// 组件卸载时清理资源
onBeforeUnmount(() => {
  // 暂停战斗相关音效，避免页面切换后音效继续播放
  AudioService.pauseBackgroundMusic();
  AudioService.clearAllSounds();
});
</script>

<template>
  <div class="battle-system">
    <!-- 对手信息 -->
    <div class="character opponent" :class="{ 'hit': opponentHit }">
      <div class="character-image-container">
        <div class="character-placeholder" :class="{ 'attacking': opponentAttacking, 'using-skill': opponentUsingSkill }">
          <div class="character-initials">{{ opponentState.name.charAt(0) }}</div>
        </div>
      </div>
      <div class="character-info">
        <h3>{{ opponentState.name }}</h3>
        <div class="health-bar">
          <div class="health-label">生命值:</div>
          <div class="health-bar-container">
            <div 
              class="health-bar-fill opponent-health" 
              :style="{ width: opponentHealthPercent + '%' }"
            ></div>
          </div>
          <div class="health-value">{{ opponentState.currentHealth }} / {{ opponentState.health }}</div>
        </div>
        <div class="chakra-bar">
          <div class="chakra-label">查克拉:</div>
          <div class="chakra-bar-container">
            <div 
              class="chakra-bar-fill opponent-chakra" 
              :style="{ width: opponentChakraPercent + '%' }"
            ></div>
          </div>
          <div class="chakra-value">{{ opponentState.currentChakra }} / {{ opponentState.chakra }}</div>
        </div>
      </div>
    </div>
    
    <!-- 战斗日志 -->
    <div class="battle-log">
      <h3>战斗日志</h3>
      <div class="log-content">
        <div v-for="log in battleLog" :key="log.id" class="log-entry">
          {{ log.message }}
        </div>
      </div>
    </div>
    
    <!-- 玩家信息和控制 -->
    <div class="character player" :class="{ 'hit': playerHit }">
      <div class="character-info">
        <h3>{{ playerState.name }}</h3>
        <div class="health-bar">
          <div class="health-label">生命值:</div>
          <div class="health-bar-container">
            <div 
              class="health-bar-fill player-health" 
              :style="{ width: playerHealthPercent + '%' }"
            ></div>
          </div>
          <div class="health-value">{{ playerState.currentHealth }} / {{ playerState.health }}</div>
        </div>
        <div class="chakra-bar">
          <div class="chakra-label">查克拉:</div>
          <div class="chakra-bar-container">
            <div 
              class="chakra-bar-fill player-chakra" 
              :style="{ width: playerChakraPercent + '%' }"
            ></div>
          </div>
          <div class="chakra-value">{{ playerState.currentChakra }} / {{ playerState.chakra }}</div>
        </div>
        
        <!-- 战斗控制按钮 -->
        <div class="battle-controls" v-if="currentTurn === 'player' && !gameOver">
          <button class="attack-button" @click="playerAttack" :disabled="isActionInProgress">
            普通攻击
          </button>
          <div class="skills-container">
            <button 
              v-for="(skill, index) in playerState.skills" 
              :key="index"
              class="skill-button"
              @click="playerUseSkill(index)"
              :disabled="isActionInProgress || playerState.currentChakra < 20"
            >
              {{ skill }} (20查克拉)
            </button>
          </div>
        </div>
        
        <!-- 战斗状态提示 -->
        <div class="battle-status" v-if="isActionInProgress">
          {{ currentTurn === 'player' ? '你正在行动...' : '对手正在行动...' }}
        </div>
        
        <!-- 战斗结果 -->
        <div class="battle-result" v-if="gameOver">
          <div v-if="battleResult === 'win'" class="win-message">
            胜利！
          </div>
          <div v-else-if="battleResult === 'lose'" class="lose-message">
            失败
          </div>
        </div>
      </div>
      <div class="character-image-container">
        <div class="character-placeholder" :class="{ 'attacking': playerAttacking, 'using-skill': playerUsingSkill }">
          <div class="character-initials">{{ playerState.name.charAt(0) }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.battle-system {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 1rem;
}

.character {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: rgba(255, 255, 255, 0.95);
  border: 2px solid var(--naruto-orange);
  border-radius: 15px;
  padding: 20px;
  margin-bottom: 15px;
  position: relative;
  overflow: hidden;
  transition: transform 0.3s ease;
}

.character::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 5px;
  background: linear-gradient(90deg, var(--naruto-red), var(--naruto-orange));
}

.character.opponent {
  flex-direction: row;
}

.character.player {
  flex-direction: row-reverse;
}

.character:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.character-image-container {
  width: 120px;
  height: 120px;
}

.character-placeholder {
  width: 100%;
  height: 100%;
  background: linear-gradient(45deg, var(--naruto-orange), var(--naruto-red));
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 2.2rem;
  font-weight: bold;
  color: white;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
  transition: transform 0.3s ease;
  position: relative;
  overflow: hidden;
}

/* 攻击动画 */
.character-placeholder.attacking {
  animation: attackAnimation 0.8s ease;
  background: linear-gradient(45deg, var(--naruto-red), #ff3300);
}

@keyframes attackAnimation {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.1) translateX(-15px); }
}

/* 技能动画 */
.character-placeholder.using-skill {
  animation: skillAnimation 1s ease;
  background: linear-gradient(45deg, var(--naruto-blue), var(--naruto-blue-light));
  box-shadow: 0 0 30px rgba(0, 123, 255, 0.6);
  /* 添加发光效果 */
  position: relative;
}

.character-placeholder.using-skill::after {
  content: '';
  position: absolute;
  top: -5px;
  left: -5px;
  right: -5px;
  bottom: -5px;
  border-radius: 50%;
  background: linear-gradient(45deg, transparent, var(--naruto-blue), transparent);
  opacity: 0.7;
  z-index: -1;
  animation: skillGlow 1s ease;
}

@keyframes skillAnimation {
  0%, 100% { transform: scale(1) rotate(0deg); }
  25% { transform: scale(1.1) rotate(5deg); }
  50% { transform: scale(1.2) rotate(-5deg); }
  75% { transform: scale(1.1) rotate(5deg); }
}

@keyframes skillGlow {
  0%, 100% { opacity: 0.3; transform: scale(1); }
  50% { opacity: 0.8; transform: scale(1.1); }
}

/* 受伤动画 */
.character.hit {
  animation: hitAnimation 0.5s ease;
}

@keyframes hitAnimation {
  0%, 100% { transform: translateX(0); opacity: 1; }
  25% { transform: translateX(10px); opacity: 0.8; background-color: rgba(255, 0, 0, 0.1); }
  50% { transform: translateX(-10px); opacity: 0.9; }
  75% { transform: translateX(5px); opacity: 1; }
}

.character:hover .character-placeholder {
  transform: scale(1.05);
}

.character-info {
  flex: 1;
  margin: 0 20px;
}

.character-info h3 {
  margin: 0 0 15px 0;
  color: var(--naruto-red);
  font-size: 1.6rem;
  font-weight: bold;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
}

.health-bar, .chakra-bar {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  background: rgba(0, 0, 0, 0.05);
  border-radius: 10px;
  padding: 8px 12px;
}

.health-label, .chakra-label {
  width: 60px;
  font-size: 0.9rem;
  font-weight: bold;
  color: var(--naruto-black);
}

.health-bar-container, .chakra-bar-container {
  flex: 1;
  height: 22px;
  background: rgba(0, 0, 0, 0.1);
  border-radius: 11px;
  overflow: hidden;
  margin: 0 10px;
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1);
}

.health-bar-fill {
  height: 100%;
  transition: width 0.5s ease;
  position: relative;
}

.health-bar-fill::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  animation: shimmer 2s infinite;
}

@keyframes shimmer {
  0% { transform: translateX(-100%); }
  100% { transform: translateX(100%); }
}

.player-health {
  background: linear-gradient(90deg, #00cc66, #00ff88);
}

.opponent-health {
  background: linear-gradient(90deg, #cc0000, #ff4444);
}

.chakra-bar-fill {
  height: 100%;
  background: linear-gradient(90deg, var(--naruto-blue), var(--naruto-blue-light));
  transition: width 0.5s ease;
  position: relative;
}

.chakra-bar-fill::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  animation: shimmer 2s infinite;
}

.health-value, .chakra-value {
  width: 80px;
  text-align: right;
  font-size: 0.9rem;
  font-weight: bold;
  color: var(--naruto-black);
}

.battle-log {
  background: rgba(255, 255, 255, 0.95);
  border: 2px solid var(--naruto-blue);
  border-radius: 15px;
  padding: 20px;
  margin-bottom: 15px;
  max-height: 250px;
  overflow-y: auto;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.battle-log h3 {
  margin: 0 0 15px 0;
  color: var(--naruto-blue);
  font-weight: bold;
}

.log-entry {
  padding: 8px 0;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  animation: fadeInLog 0.3s ease;
  color: var(--naruto-black);
}

@keyframes fadeInLog {
  from { opacity: 0; transform: translateX(-10px); }
  to { opacity: 1; transform: translateX(0); }
}

.log-entry:last-child {
  border-bottom: none;
}

.battle-controls {
  margin-top: 15px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.attack-button {
  background: linear-gradient(135deg, var(--naruto-orange), var(--naruto-red));
  color: white;
  border: none;
  padding: 12px 20px;
  font-size: 1.1rem;
  font-weight: bold;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
}

.attack-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.2);
  background: linear-gradient(135deg, var(--naruto-red), var(--naruto-red-light));
}

.skill-button {
  background: linear-gradient(135deg, var(--naruto-blue), var(--naruto-blue-light));
  color: white;
  border: none;
  padding: 10px 15px;
  margin-right: 10px;
  margin-bottom: 10px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: bold;
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.15);
}

.skill-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 5px 12px rgba(0, 0, 0, 0.2);
  background: linear-gradient(135deg, var(--naruto-blue-light), var(--naruto-blue));
}

.attack-button:disabled, .skill-button:disabled {
  background: #cccccc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.skills-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.battle-status {
  margin-top: 15px;
  text-align: center;
  font-size: 1.2rem;
  color: var(--naruto-orange);
  font-weight: bold;
  padding: 10px;
  background: rgba(255, 153, 0, 0.1);
  border-radius: 8px;
}

.battle-result {
  margin-top: 15px;
  text-align: center;
  font-size: 1.8rem;
  font-weight: bold;
  padding: 15px;
  border-radius: 10px;
  animation: resultPulse 1s ease infinite alternate;
}

@keyframes resultPulse {
  from { transform: scale(1); }
  to { transform: scale(1.05); }
}

.win-message {
  color: #00cc66;
  background: rgba(0, 204, 102, 0.1);
}

.lose-message {
  color: #cc0000;
  background: rgba(204, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .character {
    flex-direction: column !important;
    text-align: center;
    padding: 15px;
  }
  
  .character-info {
    margin: 15px 0 0 0;
  }
  
  .health-bar, .chakra-bar {
    flex-wrap: wrap;
    text-align: center;
  }
  
  .health-label, .chakra-label {
    width: 100%;
    margin-bottom: 5px;
  }
  
  .health-value, .chakra-value {
    width: 100%;
    text-align: center;
    margin-top: 5px;
  }
  
  .character-image-container {
    width: 100px;
    height: 100px;
  }
  
  .character-placeholder {
    font-size: 1.8rem;
  }
  
  .skills-container {
    justify-content: center;
  }
  
  .skill-button {
    margin-right: 5px;
    margin-left: 5px;
  }
}
</style>